package com.rzjm.api.netty;

import cn.hutool.core.util.StrUtil;
import com.rzjm.api.entity.DeviceRange;
import com.rzjm.api.service.DeviceRangeRecordService;
import com.rzjm.api.service.DeviceRangeService;
import com.rzjm.api.util.DateUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

/**
 * @创建者：zhouwei
 * @创建时间：2021/5/24
 * @描述：
 */
@Component
public class MessageDecode {
    @Resource
    private DeviceRangeService deviceRangeService;
    @Resource
    private DeviceRangeRecordService deviceRangeRecordService;
    /*添加代码 begin*/
    private static MessageDecode messageDecode;

    @Resource
    protected RedisTemplate<String, Object> redisTemplate;

    @PostConstruct
    public void init(){
        messageDecode = this;
        messageDecode.deviceRangeService = this.deviceRangeService;
        messageDecode.deviceRangeRecordService = this.deviceRangeRecordService;
        messageDecode.redisTemplate = this.redisTemplate;
    }

    public static String onMessage(MessageModel model,String dataCode){
        String msg = "";
        if(model.getMsgType() == null){
            return "";
        }
        try{
            if(model.getMsgType() == 0){
                //01 心跳
                if(model.getOrder().equals("01")){//心跳
                    msg = model.getHeader() + model.getOrder() + model.getClientNum() + DateUtil.getSdfTimes() + model.getFooter();

                    String data = model.getData();
//                    System.out.println("心跳数据：" + data);
                    if(data.contains(",")) {
                        String[] dataArray = data.split(",");
                        //修改温湿度
                        updateDeviceData(model.getClientNum(),dataArray);
                    }
                }
                //02 初始化
                else if(model.getOrder().equals("02")){//初始化
                    msg = model.getHeader() + model.getOrder() + model.getClientNum()  + DateUtil.getSdfTimes() + model.getFooter();
                    //31,89860621290057129022,,1.0,
                    //36.1,ICCID,IMEI,539,01
                    String data = model.getData();
                    //MS 02 22000030 31,89860621290057129022,,1.0,ME
                    //31,89860621290057129022,,1.0, 信号强度，ICCID，IMEI，版本
                    //信号强度,电话卡id，电话卡MEI,插座数量，程序版本
                    if(data.contains(",")){
                        String[] dataArray = data.split(",");
                        if(dataArray.length >= 3){
                            if(StrUtil.isNotEmpty(dataArray[1])){
                                updateDeviceSimCardNum(model.getClientNum(),dataArray);
                            }
                        }
                    }
                }
                // 03 获取单次距离值
                else if(model.getOrder().equals("03")){
                    //01表示收到
                    msg = model.getHeader()  + model.getOrder() + model.getClientNum() +  "01" + model.getFooter();
                    String data = model.getData();
                    if(data.contains(",")) {
//                        MS 05 12000014 00,00000001652362401153,,ME
//                        00,00000001652362401153,,
//                        端口号，订单号,故障信息（一个字节）
                        String[] dataArray = data.split(",");

                        addSingleRecord(model.getClientNum(), dataArray,data, model.getOrder());
                    }
                }
                //04 获取全角度距离值
                else if(model.getOrder().equals("04")){
                    msg = model.getHeader()  + model.getOrder() + model.getClientNum() +  "01" + model.getFooter();
                    String data = model.getData();

                    //01表示收到，之后将按照单次获取距离值的回传方式，连续上传90次角度值
                    if(data.contains(",")) {//上传数据
                        //,123,123,123,122,122,120,120,121,121,122,122,123,121,121,120,121,123,123,118,118,116,113,111,114,70,50,44,37,22,13,9,6,5,4,4,
                        // 3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,
                        // 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
                        //掐头去尾  去掉逗号
                        data = data.substring(1,data.length() - 1);
//                        MS 10 22100001 01,1,00000001653574155250 ME
//                        端口号，订单号,故障信息（一个字节）
//                        MS 10 20220522 09,0,00000001660480532696 ME
                        String[] dataArray = data.split(",");
                        if(dataArray.length == 2){
                            addSingleRecord(model.getClientNum(), dataArray, data, model.getOrder());
                        }
                    }else if(data.equals("01")){

                    }
                }
                //05 清洗雷达镜头
                else if(model.getOrder().equals("05")){

                }
                //06 接收一次性90个角度的数据
                else if(model.getOrder().equals("06")){
                    msg = model.getHeader()  + model.getOrder() + model.getClientNum() +  "01" + model.getFooter();
                    String data = model.getData();
                    System.out.println("06命令获取数据：" + data);
                    //01表示收到，之后将按照单次获取距离值的回传方式，连续上传90次角度值
//                    接收消息: MS062300000214808ME
//                            带有结束标志
//                    接收后的数据：MS062300000214808ME
//                    接收到消息：MS0623000002 14808 ME

                    if(data.contains(",")) {//上传数据
                        //,123,123,123,122,122,120,120,121,121,122,122,123,121,121,120,121,123,123,118,118,116,113,111,114,70,50,44,37,22,13,9,6,5,4,4,
                        // 3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,
                        // 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
                        //掐头去尾  去掉逗号
                        data = data.substring(1,data.length() - 1);
//                        MS 10 22100001 01,1,00000001653574155250 ME
//                        端口号，订单号,故障信息（一个字节）
//                        MS 10 20220522 09,0,00000001660480532696 ME
                        String[] dataArray = data.split(",");
                        if(dataArray.length == 90){
                            addMultiplyRecord(model.getClientNum(), dataArray, data, model.getOrder());
                        }
                    }else{
                        //String deviceNum, String[] dataArray, String data, String orderNum
                        addSingleRecordOil(model.getClientNum(), data, model.getOrder());
                    }
                }else if(model.getOrder().equals("07")){
                    msg = model.getHeader()  + model.getOrder() + model.getClientNum() +  "001" + model.getFooter();
                    String data = model.getData();
                    System.out.println("07命令获取数据：" + data);
                    if(data.contains(",")) {//上传数据
//                        data = data.substring(1,data.length() - 1);
//                        MS 10 22100001 01,1,00000001653574155250 ME
//                        端口号，订单号,故障信息（一个字节）
//                        MS 10 20220522 09,0,00000001660480532696 ME
                        String[] dataArray = data.split(",");
                        if(dataArray.length == 2){
                            addSingleRecord(model.getClientNum(), dataArray, data, model.getOrder());
                        }
                    }
                }
                if(model.getOrder().equals("01")){
                    updateDeviceOnlineState(model.getClientNum(),1);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return msg;
    }


    public static DeviceRange getDeviceInfo(String deviceNum){
        DeviceRange devices = messageDecode.deviceRangeService.getDeviceInfoByNum(deviceNum);
        if(devices == null){
            devices = new DeviceRange();
            devices.setDeviceNum(deviceNum);
            devices.setState(1);
            devices.setCreateTime(new Date());
            devices.setDeviceType(0);
            devices.setDeviceName("测试" + deviceNum);
            //默认桶高
            devices.setCylinderHeight(16d);
            //默认直径
            devices.setStoreDiameter(14d);
            devices.setIsEllipse(0);
            devices.setConeHeight(5d);
            devices.setLongHalfShaft(0d);
            devices.setShortHalfShaft(0d);
            devices.setShopId(54);//测试企业
            devices.setIsLie(0);//立式
            devices.setOnlineState(1);
            devices.setLastOnlineTime(new Date());
            int ret = messageDecode.deviceRangeService.initDevice(devices);
        }
        return devices;
    }


    /**
     *  更改设备在线状态
     * @param deviceNum
     * @param onlineState
     */
    public static void updateDeviceOnlineState(String deviceNum,int onlineState){
        DeviceRange range = messageDecode.deviceRangeService.getDeviceInfoByNum(deviceNum);
        if(range != null){
            range.setOnlineState(onlineState);
            range.setLastOnlineTime(new Date());
            if(onlineState == 0){
                range.setLastOfflineTime(new Date());
            }else{
                range.setLastOnlineTime(new Date());
            }
            messageDecode.deviceRangeService.resetDevice(range);
        }
    }


    /**
     *  更改设备当前温湿度
     * @param deviceNum
     * @param dataArray
     */
    public static void updateDeviceData(String deviceNum, String[] dataArray){
        try{
            DeviceRange range = messageDecode.deviceRangeService.getDeviceInfoByNum(deviceNum);
            if(range != null){
                if(dataArray.length > 0){
                    range.setTemperature(dataArray[0]);
                    if(dataArray.length == 2){
                        range.setHumidity(dataArray[1]);
                        if(dataArray[1].equals("0")){
                            double temp = Double.parseDouble(range.getTemperature()) * 0.1;
                            range.setTemperature(String.valueOf(temp));
                        }
                    }
                    messageDecode.deviceRangeService.resetDevice(range);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     *  03 命令  添加 单条 记录
     * @param deviceNum
     * @param data
     * @param orderNum
     */
    public static void addSingleRecord(String deviceNum, String[] dataArray, String data,String orderNum){
        DeviceRange range = messageDecode.deviceRangeService.getDeviceInfoByNum(deviceNum);
        if(range != null){
            messageDecode.deviceRangeRecordService.addSingleRecord(deviceNum, dataArray, data, orderNum);
        }
    }


    /**
     *  06 命令  添加 单条 记录
     * @param deviceNum
     * @param data
     * @param orderNum
     */
    public static void addSingleRecordOil(String deviceNum, String data,String orderNum){
        DeviceRange range = messageDecode.deviceRangeService.getDeviceInfoByNum(deviceNum);
        if(range != null){
            messageDecode.deviceRangeRecordService.addSingleRecordOil(deviceNum, data, orderNum);
        }
    }


    /**
     *  06 命令  添加 多条 记录
     * @param deviceNum
     * @param data
     * @param orderNum
     */
    public static void addMultiplyRecord(String deviceNum, String[] dataArray, String data,String orderNum){
        DeviceRange range = messageDecode.deviceRangeService.getDeviceInfoByNum(deviceNum);
        if(range != null){
            messageDecode.deviceRangeRecordService.addMultiplyRecord(deviceNum, dataArray, data, orderNum);
        }
    }

    /**
     *  更改设备SIM卡编号
     * @param deviceNum
     * @param dataArray
     */
    public static void updateDeviceSimCardNum(String deviceNum,String[] dataArray){
        DeviceRange charger = messageDecode.deviceRangeService.getDeviceInfoByNum(deviceNum);
        if(charger != null){
            ////信号强度,电话卡id，电话卡iMEI,插座数量，程序版本
            charger.setSimCardNum(dataArray[1]);
            charger.setSimImei(dataArray[2]);
            messageDecode.deviceRangeService.resetDevice(charger);
        }
    }
}
